package com.capybara.account.service.impl;

import com.capybara.account.config.MyConfig;
import com.capybara.account.exception.MyServiceException;
import com.capybara.account.service.IFileService;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;

/**
 * 文件服务impl
 *
 * @author guochaowang
 * @date 2023/03/07
 */
@Service()
public class FileServiceImpl implements IFileService {
    @Resource
    private MyConfig myConfig;
    @Resource
    private ServerProperties serverProperties;

    /**
     * 放置本地文件
     *
     * @param file 文件
     * @param type 存储位置设置
     * @return 字符串
     */
    @Override
    public String putLocalFile(MultipartFile file, String type) throws IOException {
        InputStream inputStream = file.getInputStream();
        String filePath;
        LocalDate now = LocalDate.now();
        String format;
        if (myConfig.getFilePath().contains("/")) {
            if (type == null) {
                type = "/static";
            } else {
                type = "/static/" + type;
            }
            format = String.format("%s/%d/%02d/%d/", type, now.getYear(), now.getMonthValue(), now.getDayOfMonth());
        } else {
            if (type == null) {
                type = "\\static";
            } else {
                type = "\\static\\" + type;
            }
            format = String.format("%s\\%d\\%02d\\%d\\", type, now.getYear(), now.getMonthValue(), now.getDayOfMonth());
        }
        boolean b = new File(myConfig.getFilePath() + format).mkdirs();
        if (!b) {
            throw new MyServiceException("创建目录失败");
        }
        String fileName = file.getOriginalFilename();
        filePath = format + System.currentTimeMillis() + fileName;
        FileOutputStream outputStream = new FileOutputStream(myConfig.getFilePath() + filePath);
        StreamUtils.copy(inputStream, outputStream);
        outputStream.close();
        String replace = filePath.replace("\\", "/");
        return serverProperties.getServlet().getContextPath() != null ? serverProperties.getServlet().getContextPath() + replace : replace;
    }


}
